package com.hyt.it.ogt.kq.service.gov.service.impl;

import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.kq.common.config.ConfigManager;
import com.hyt.it.ogt.kq.service.gov.mapper.SysFileMapper;
import com.hyt.it.ogt.kq.service.gov.model.entity.SysFile;
import com.hyt.it.ogt.kq.service.gov.service.ISysFileService;
import com.hyt.it.ogt.kq.service.gov.service.obs.CloudObsService;
import com.hyt.it.ogt.kq.common.gov.utils.HuaweiCloudObsUtil;
import com.obs.services.model.ObjectMetadata;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;


/**
 * <p>
 * 文件表 服务实现类
 * </p>
 *
 * @author huangyh
 * @since 2021-09-02
 */

@Slf4j
@Service
public class SysFileServiceImpl extends BaseServiceImpl<SysFileMapper, SysFile> implements ISysFileService {

    @Resource
    private CloudObsService cloudObsService;

    @Resource
    private ConfigManager configManager;

    @Override
    public String uploadHuaweiCloudAndSaveSysFile(String filePathName, MultipartFile file, String fileType) throws Exception {
        return this.uploadHuaweiCloudAndSaveSysFile(file.getOriginalFilename(),filePathName,file.getInputStream(),fileType);
    }

    @Override
    public String uploadHuaweiCloudAndSaveSysFile(String fileName,String filePathName, InputStream inputStream, String fileType) {
        //1.考试协议包上传到云存储
        String url = cloudObsService.updateFile(filePathName, inputStream);
        ObjectMetadata objectMetadata = HuaweiCloudObsUtil.getObjectMetadata(filePathName);
        String etag = objectMetadata.getEtag().replaceAll("\"","");
        //2.保存到系统文件
        SysFile sysFile = new SysFile();
        sysFile.setName(fileName)
                .setPath(filePathName)
                .setUrl(url)
                .setMd5(etag)
                .setType(fileType);
        save(sysFile);
        return sysFile.getId();
    }

    @Override
    public String getFilePathName(String taskCode,String businessFolderName,String fileOriginalName) {
        String path = StringUtils.join(configManager.getCloudRootPath(),
                taskCode, "/",businessFolderName, "/",System.currentTimeMillis(),
                fileOriginalName);
        return path;
    }

    @Override
    public SysFile getBaseDataByTaskCode(String taskCode) {
        return baseMapper.getBaseDataByTaskCode(taskCode);
    }

    @Override
    public SysFile getSysFileById(String fileId) {

        return this.lambdaQuery()
                .eq(SysFile::getId,fileId)
                .last("limit 1")
                .one();
    }

}
